package com.example.piece.ui.demo

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.LinearLayoutManager
import com.therouter.router.Route
import com.example.base.aop.permission.PermissionRequest
import com.example.base.ext.toast
import com.example.piece.R
import com.example.piece.constant.RoutePath
import com.example.piece.databinding.TestActivityBluetoothBinding
import com.example.piece.ui.activity.Layer3Activity
import com.example.piece.ui.demo.adapter.MyDevice
import com.example.piece.ui.demo.adapter.MyDeviceAdapter

/**
 * 蓝牙测试
 */
@SuppressLint("MissingPermission")
@Route(path = RoutePath.TESTActivity.BLUETOOTH_TEST_ACTIVITY)
class BluetoothTestActivity : Layer3Activity<TestActivityBluetoothBinding, ViewDataBinding>() {


    override val isTransparentStatusBar: Boolean = false

    override val isDarkMode: Boolean = false
    override val centerLayoutRes: Int
        get() = R.layout.test_activity_bluetooth
    override val title: String
        get() = "蓝牙测试"
    override val leftIcon1Res: Int
        get() = R.drawable.ic_back

    //获取系统蓝牙适配器
    private lateinit var mBluetoothAdapter: BluetoothAdapter

    //扫描者
    private  var scanner: BluetoothLeScanner?=null

    //是否正在扫描
    var isScanning = false

    //设备列表
    private val deviceList = mutableListOf<MyDevice>()

    //适配器
    private lateinit var myDeviceAdapter: MyDeviceAdapter

    //扫描结果回调
    private val scanCallback = object : ScanCallback() {
        override fun onScanResult(callbackType: Int, result: ScanResult) {
            addDeviceList(MyDevice(result.device, result.rssi))
        }
    }
    //打开蓝牙意图
    private val enableBluetooth =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == Activity.RESULT_OK) {
                if (isOpenBluetooth()) {
                    mBluetoothAdapter =
                        (getSystemService(BLUETOOTH_SERVICE) as BluetoothManager).adapter
                    scanner = mBluetoothAdapter.bluetoothLeScanner
                    toast("蓝牙已打开")
                } else {
                    toast("蓝牙未打开")
                }
            }
        }

    override fun onClickLeftIcon1(view: View) {
        super.onClickLeftIcon1(view)
        onBackPressed()
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)
        initView()
    }
    @RequiresApi(Build.VERSION_CODES.M)
    private fun initView() {

        if (isOpenBluetooth()) {
            mBluetoothAdapter = (getSystemService(BLUETOOTH_SERVICE) as BluetoothManager).adapter
            scanner = mBluetoothAdapter.bluetoothLeScanner
        }
        //打开蓝牙
        mCenterViewBinding?.btnOpenBluetooth?.setOnClickListener {
            //蓝牙是否已打开
            //是Android12
            if (isAndroid12()) {

                //打开蓝牙
                openBlueTooth()


            }else{
                openBlueTooth()
            }


        }

        //扫描蓝牙
        mCenterViewBinding?.btnScanBluetooth?.setOnClickListener {
            scanBluetooth()
        }

        //初始化列表
        myDeviceAdapter = MyDeviceAdapter(deviceList)
        mCenterViewBinding?.rvDevice?.layoutManager = LinearLayoutManager(this)
        mCenterViewBinding?.rvDevice?.adapter = myDeviceAdapter
    }



    /**
     * 添加到设备列表中
     */
    private fun addDeviceList(device: MyDevice) {
        val index = findDeviceIndex(device, deviceList)
        if (index == -1) {
            Log.d("TAG", "name: ${device.device.name}, address: ${device.device.address}")
            deviceList.add(device)
            myDeviceAdapter.notifyDataSetChanged()
        } else {
            deviceList[index].rssi = device.rssi
            myDeviceAdapter.notifyItemChanged(index)
        }
    }

    /**
     * 在扫描结果列表中查找现有设备的索引。
     *
     * @param  scanDevice 扫描到的设备
     * @return 如果未找到，则为 return -1 的索引 则是没有添加过
     */
    private fun findDeviceIndex(scanDevice: MyDevice, deviceList: List<MyDevice>): Int {
        var index = 0
        for (device in deviceList) {
            if (scanDevice.device.address.equals(device.device.address)) return index
            index += 1
        }
        return -1
    }




    private fun scanBluetooth() {
        if (isAndroid12()) {

            //扫描或者停止扫描
            if (isScanning) stopScan() else startScan()


        } else {
            //开始扫描
            if (isScanning) stopScan() else startScan()

        }
    }

    @PermissionRequest(
        value = [
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.ACCESS_FINE_LOCATION
        ]
    ,Build.VERSION_CODES.S
    )
    private fun openBlueTooth() {
        if (isOpenBluetooth()) {
            toast("蓝牙已打开")
            return
        }
        enableBluetooth.launch(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE))
    }


    //扫描
    @PermissionRequest(
        value = [
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.BLUETOOTH_SCAN
        ],Build.VERSION_CODES.S
    )
    private fun startScan() {
        if (!isScanning) {
            scanner?.startScan(scanCallback)
            isScanning = true
            mCenterViewBinding?.btnScanBluetooth?.text = "停止扫描"
        }
    }

    //扫描
    @PermissionRequest(
        value = [
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.BLUETOOTH_SCAN
        ],Build.VERSION_CODES.S
    )
    private fun stopScan() {
        if (isScanning) {
            scanner?.stopScan(scanCallback)
            isScanning = false
            mCenterViewBinding?.btnScanBluetooth?.text = "扫描蓝牙"
        }
    }

    private fun isOpenBluetooth(): Boolean {
        val manager = getSystemService(BLUETOOTH_SERVICE) as BluetoothManager
        val adapter = manager.adapter ?: return false
        return adapter.isEnabled
    }

    private fun isAndroid12() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S


}